package com.bxj.mybatis.generator.plugin;

import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

/**
 * Created by baixiujiang on 17/10/3.
 */
public class SelectSelectiveGenerator extends AbstractXmlElementGenerator {
    public SelectSelectiveGenerator(boolean b) {
    }

    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$

        answer.addAttribute(new Attribute(
                "id", MybatisUtils.getTableProperties(introspectedTable, "selectSelectiveStatementId", "selectSelective"))); //$NON-NLS-1$

        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
                .calculateAllFieldsClass();

        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
                parameterType.getFullyQualifiedName()));

        answer.addAttribute(new Attribute("resultMap", //$NON-NLS-1$
                "BaseResultMap"));

        context.getCommentGenerator().addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("select ");
        answer.addElement(new TextElement(sb.toString()));

        XmlElement columnElement = new XmlElement("include"); //$NON-NLS-1$
        columnElement.addAttribute(new Attribute("refid", "Base_Column_List"));
        answer.addElement(columnElement);

        sb.setLength(0);
        sb.append(" from "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        XmlElement whereElement = new XmlElement("include"); //$NON-NLS-1$
        whereElement.addAttribute(new Attribute("refid", "Where_Clause"));
        answer.addElement(whereElement);

        XmlElement orderByElement = new XmlElement("include"); //$NON-NLS-1$
        orderByElement.addAttribute(new Attribute("refid", "OrderBy_Clause"));
        answer.addElement(orderByElement);

        XmlElement paginationElement = new XmlElement("include"); //$NON-NLS-1$
        paginationElement.addAttribute(new Attribute("refid", "MySql_Pagination"));
        answer.addElement(paginationElement);


        if (context.getPlugins().sqlMapInsertSelectiveElementGenerated(
                answer, introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}
